package com.user.config;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.user.domain.User;
import com.user.mapper.UserMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * @Author : Yu
 * @Date 2024/1/5 17:16
 * @Description : 自定义权限验证扩展
 */

@Component    // 保证此类被 SpringBoot 扫描，完成 Sa-Token 的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private UserMapper userMapper;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return null;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        int role = getRole(loginId.toString());
        List<String> list = new ArrayList<>();
        if (role == 0) list.add("user");
        else if (role == 1) list.add("admin");
        return list;
    }


    private int getRole(String loginId) {
        long phone = Long.parseLong(loginId);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(User::getRole).eq(User::getPhone, phone);
        User user = userMapper.selectOne(wrapper);
        return user.getRole();
    }

}

